﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Login1.RememberMeText = "今天自动登录";
        if (Session["currentUser"] != null) {
            Response.Redirect("success.aspx");
        }
        if (Session["message"] != null) {
            this.Label1.Text = "注册成功！请登录。";
        }
    }
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string username=this.Login1.UserName;
        string password = this.Login1.Password;
        SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=test;User ID=sa;Password=sa123456");
        myConn.Open();
        SqlCommand command = new SqlCommand("");
        SqlDataAdapter adapter = new SqlDataAdapter();
        DataSet ds = new DataSet();
        SqlCommand cmd = new SqlCommand();
        SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(adapter);
        adapter.SelectCommand = cmd;
        cmd.Connection = myConn;
        

        adapter.SelectCommand.CommandText = "select * from student where name=@name and password=@password";
        adapter.SelectCommand.Parameters.AddWithValue("@name", username);
        adapter.SelectCommand.Parameters.AddWithValue("@password", password);
        adapter.Fill(ds,"123");
        int count = ds.Tables["123"].Rows.Count;
        if (count == 0)
        {
            close(myConn, ds, cmd, adapter);
            Response.Write("<script>alert('用户名或密码错误！');</script>");
            return;
        }
        else 
        {
            string age = ds.Tables["123"].Rows[0]["age"].ToString();
            if (Login1.RememberMeSet == true)
            {
                Session["currentUser"] = new User(username, age);
                Session["remeber"] = "1";
                Session.Timeout=1440;
                Response.Redirect("success.aspx");
                
            }
            else 
            {
                Session["currentUser"] = new User(username, age);
                Response.Redirect("success.aspx");
            }
        }
    }
    private void close(SqlConnection myConn, DataSet ds, SqlCommand cmd, SqlDataAdapter adapter)
    {
        if (myConn != null && myConn.State == ConnectionState.Open)
        {
            try
            {
                myConn.Close();
                myConn.Dispose();
            }
            catch
            {
                return;
            }
        }
        if (ds != null)
            ds.Dispose();
        if (cmd != null)
            cmd.Dispose();
        if (adapter != null)
            adapter.Dispose();
    }
}